//
//  NetworkManager.swift
//  微博
//
//  Created by xm on 2018/3/21.
//  Copyright © 2018年 xm. All rights reserved.
//

import UIKit
import AFNetworking

//swi枚举支持任意类型
//oc中 enum/switch都支持整数
enum HttpMethod{
    case GET
    case POST
}

//网络工具
class NetworkManager: AFHTTPSessionManager {
    //静态区 常量 /闭包（单利模式）
    //第一次运行时，执行闭包保存到shared常量中
    static let shared:NetworkManager={
        let afn=NetworkManager()
        afn.responseSerializer.acceptableContentTypes?.insert("text/html")//指定可以解析的类型
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")//指定可以解析的类型
        return afn
    }()
    
    lazy var userAccount=UserAccount() //= "2.00JgpAvGSsJoUC8b912c4f11Hhrz6C" 
    var userLogined:Bool{//用户是否登录了
        return userAccount.access_token != nil
    }
    
    func requestWithToken(method:HttpMethod = .GET,URLString:String,parameters:[String:Any]?,
                          completion:@escaping (Any?,Bool) ->()){
        if !userLogined {
           NotificationCenter.default.post(name: NSNotification.Name(WBTokenErrorNotification), object: nil)
            return
        } 
        var parameters=parameters;
        if parameters == nil {
            parameters = [String : AnyObject]()
        }
        parameters!["access_token"]=userAccount.access_token
        request(method: method, URLString: URLString, parameters: parameters!, completion: completion)
    }
    
    func request(method:HttpMethod = .GET,URLString:String,parameters:[String:Any],
                 completion:@escaping (Any?,Bool) ->() ) {
        
        let success={(tak:URLSessionDataTask,json:Any?)->() in
            completion(json,true)
        }
        
        let failure={(tak:URLSessionDataTask?,error:Error)->() in
            
            if (tak?.response as? HTTPURLResponse)?.statusCode == 403{
                NotificationCenter.default.post(name: NSNotification.Name(WBTokenErrorNotification), object: nil)
            }
            completion(error, false)
        }
        
        if method == .GET {
             get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
      
        
    }
}
